package cn.edu.ctgu.ch1.performance;

import cn.edu.ctgu.ch1.WordsService;
import cn.edu.ctgu.ch1.cache.CachedWordsService;
import cn.edu.ctgu.ch1.config.WordConfig;
import cn.edu.ctgu.ch1.initial.DefaultWordService;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * To start this benchmark, run the {@link WordExistsPerformanceTestRunner#main(String[])} method}
 *
 * @author tiger54910
 * @create 2025/1/31 20:37
 */
@Fork(1)
@Warmup(iterations = 1,time = 1)
@Measurement(iterations = 5,time = 1)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)

public class WordExistsPerformanceBenchmark {
  private static final int NUMBER_OF_CHECKS = 100;
  private static final List<String> WORDS_TO_CHECK =
      Arrays.asList("made", "ask", "find", "zones", "lask", "123");

  @Benchmark
  public void baseline(Blackhole blackhole) {
    WordConfig wordConfig = getWordConfig();
    WordsService defaultWordsService = new DefaultWordService(wordConfig);
    for (int i = 0; i < NUMBER_OF_CHECKS; ++i) {
      for (String word : WORDS_TO_CHECK) {
        blackhole.consume(defaultWordsService.wordExists(word));
      }
    }
  }

  @Benchmark
  public void cache(Blackhole blackhole) {
    WordConfig wordConfig = getWordConfig();
    WordsService defaultWordsService = new CachedWordsService(wordConfig);
    for (int i = 0; i < NUMBER_OF_CHECKS; ++i) {
      for (String word : WORDS_TO_CHECK) {
        blackhole.consume(defaultWordsService.wordExists(word));
      }
    }
  }

  private static WordConfig getWordConfig() {
    WordConfig wordConfig = new WordConfig();
    wordConfig.setDictionary("src/main/resources/words.txt");
    return wordConfig;
  }
}
